package com.axapoint.opoc.core.dao;

import java.util.ArrayList;

import org.joda.time.DateTime;
import org.joda.time.Interval;

import com.axapoint.opoc.core.UserException;

public class PostalDistrictFacade extends AbstractFacade<PostalDistrict, PostalDistrict.Value, PostalDistrict.Bitemporal> {

	public PostalDistrictFacade(String systemId, String userId) {
		super(systemId, userId, new PostalDistrict(), new PostalDistrict.Value());
	}
	
	public Location.Value[] getLocations(String uuid, DateTime at) {
		PostalDistrict pd = getEntity(uuid);
		if (pd == null) throw new UserException("Ingen Postkode med UUID: " + uuid);
		
		ArrayList<Location.Value> result = new ArrayList<Location.Value>();
        for (Location.Value v : pd.getLocations()) {
        	if (at == null || v.getBitemporal().getValidityInterval().contains(at)) {
        		result.add(v);
        	}
        }
		
		return result.toArray(new Location.Value[0]);
	}

	@Override
	public ObjectRegistration[] getAffectedEntities(String uuid, Interval newInterval) {
		ArrayList<ObjectRegistration> result = new ArrayList<ObjectRegistration>(); 
		
		PostalDistrict pd = getEntity(uuid);
		for (Location.Value l : pd.getLocations()) {
			Interval i = l.getEntity().getValues().get(newInterval.getStart()).getValidityInterval();
			
			// If the location does not have interval this can contain new postal district it is affected
			if (!i.contains(newInterval)) {
				result.add(l.getEntity());
			}
		}
		
		// Find affected Locations
		
		
		//XXX: implement
		return result.toArray(new ObjectRegistration[0]);
	}

}